import json

from django.shortcuts import render
from django.views import View
from apps.testcase.models import ApiCaseModel
from django.http import JsonResponse
from apps.testcase.models import ApiCase
# Create your views here.


class ApiCaseIndex(View):

    def get(self, request):
        # 查询model
        models = ApiCaseModel.objects.all()
        # 查询第一个model 下的所有apicase
        cases = ApiCase.objects.filter(model_id=models[0].id)
        return render(request, 'testcase/index.html', {'models': models, 'cases': cases, 'modelid': models[0].id})

    def post(self, request):
        modelid = request.POST.get('modelid')
        if not modelid:
            return JsonResponse({'code': 101, "data": {'msg': '参数错误'}}, status=101)
        cases = ApiCase.objects.filter(model_id=modelid)
        # print(cases.values())
        i_list = []
        for i in cases.values():
            for key, value in i.items():
                if value is None:
                    i[key] = ""
            i_list.append(i)
        data = {}
        data.update({'data': i_list})
        return JsonResponse({'code': 200, 'data': data}, status=200)


class ApiCaseAdd(View):

    def get(self, request):
        return JsonResponse({'code': 403, 'errmsg': '访问异常，请重试'}, status=403)

    def post(self, request):
        data_d = request.body
        print(eval(data_d.decode()), type(eval(data_d.decode())))
        return JsonResponse({'data': str(data_d)})


class ApiCaseDel(View):
    def get(self, request):
        return JsonResponse({'code': 403, 'errmsg': '访问异常，请重试'}, status=403)

    def post(self, request):
        id = request.POST.get('id')
        data = ApiCase.objects.filter(id=id)
        if data:
            data.delete()
            return JsonResponse({'code': 200, 'errmsg': '删除成功'}, status=200)
        else:
            return JsonResponse({'code': 201, 'errmsg': '记录不存在'}, status=201)

